package com.intmall.flink.operator;

import org.apache.flink.api.common.functions.RichFunction;
import org.apache.flink.api.common.functions.RichMapFunction;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;

public class TransformRichFunctionTest {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        DataStreamSource<Event> stream = env.fromElements(
                new Event("Mary", "./home", 1000L),
                new Event("Bob", "./cart", 2000L),
                new Event("Alice", "./cart", 2100L),
                new Event("Bob", "./product?id=1", 3000L),
                new Event("Bob", "./product?id=2", 3500L),
                new Event("Bob", "./product?id=3", 4000L),
                new Event("Bob", "./product?id=3", 3600L),
                new Event("Alice", "./product?id=1", 5100L),
                new Event("Mary", "./center", 6000L)
        );

        stream.map(new MyMapper()).print();

        env.execute();
    }

    public static class MyMapper extends RichMapFunction<Event, Integer> {

        @Override
        public void open(Configuration parameters) throws Exception {
            super.open(parameters);
            System.out.println("open索引为 " + getRuntimeContext().getIndexOfThisSubtask() + " 的任务开始");
        }

        @Override
        public Integer map(Event value) throws Exception {
            return value.getUrl().length();
        }

        @Override
        public void close() throws Exception {
            super.close();
            System.out.println("close索引为 " + getRuntimeContext().getIndexOfThisSubtask() + " 的任务结束");
        }
    }
}
